<template>
  <!-- 顶部导航 -->
  <div class="header">
    <div class="nav-links">
      <button @click="handleLogout" class="logout-btn">登出</button>
    </div>
  </div>

  <!-- 主体内容 -->
  <div class="main">
    <!-- 左侧菜单 -->
    <div class="sidebar">
      <div class="logo">
        <img src="@/assets/Logo.png" alt="Logo" />
      </div>
      <div class="system-title">管理系统</div>
      <ul class="menu">
        <li><router-link to="/manager" class="menu-link">首页</router-link></li>
        <li class="parent-menu" @click="toggleMenu('user')">
          <span class="menu-item">
            <span>用户管理</span>
            <span class="toggle-icon">{{ expanded.user ? '∨' : '^' }}</span>
          </span>
          <ul v-show="expanded.user" class="submenu">
            <li><router-link to="/userlist" class="submenu-link">用户列表</router-link></li>
            <li><router-link to="/adminlist" class="submenu-link">管理员列表</router-link></li>
          </ul>
        </li>
        <li class="parent-menu" @click="toggleMenu('product')">
          <span class="menu-item">
            <span>商品管理</span>
            <span class="toggle-icon">{{ expanded.product ? '∨' : '^' }}</span>
          </span>
          <ul v-show="expanded.product" class="submenu">
            <li><router-link to="/productlist" class="submenu-link">商品列表</router-link></li>
          </ul>
        </li>
      </ul>
    </div>

    <!-- 右侧内容（完全保留原表格结构） -->
    <div class="content">
      <div class="content-header">
        <div class="search-bar">
          <input type="text" placeholder="输入管理员名进行操作" v-model="searchKeyword" @focus="onFocus" />

        </div>
        <div class="btn-group">
          <button class="btn-add" @click="showAddModal = true">增加</button>

        </div>
      </div>

      <table>
        <thead>
          <tr>
            <th>#</th>
            <th>管理员名</th>
            <th>手机号</th>
            <th>权限</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in filteredAdmins" :key="item.id" @click="selectItem(item)"
            :class="{ 'selected': selectedItem && selectedItem.id === item.id }">
            <td>{{ index + 1 }}</td>
            <td>{{ item.username }}</td>
            <td>{{ item.phone }}</td>
            <td>{{ item.role }}</td>
            <td>
              <button @click.stop="openEditModal(item)" class="btn btn-sm btn-warning">修改</button>
              <button @click.stop="openDeleteModal(item)" class="btn btn-sm btn-danger">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
      <!-- 新增管理员弹窗 -->
      <div v-if="showAddModal" class="modal-overlay">
        <div class="modal-content">
          <h3>新增管理员</h3>
          <div class="form-group">
            <label>管理员名：</label>
            <input v-model="newAdmin.username" placeholder="请输入管理员名" required />
          </div>
          <div class="form-group">
            <label>手机号：</label>
            <input v-model="newAdmin.phone" placeholder="请输入手机号" required />
          </div>
          <div class="form-group">
            <label>权限：</label>
            <select v-model="newAdmin.role">
              <option value="正常">正常</option>
              <option value="超级管理员">超级管理员</option>
              <option value="只读">只读</option>
            </select>
          </div>
          <div class="modal-footer">
            <button @click="cancelAdd" class="btn btn-secondary">取消</button>
            <button @click="confirmAdd" class="btn btn-primary" :disabled="!isValid">确认</button>
          </div>
        </div>
      </div>

      <!-- 编辑管理员弹窗 -->
      <div v-if="showEditModal" class="modal-overlay">
        <div class="modal-content">
          <h3>编辑管理员</h3>
          <div class="form-group">
            <label>管理员名：</label>
            <input v-model="newAdmin.username" placeholder="请输入管理员名" required />
          </div>
          <div class="form-group">
            <label>手机号：</label>
            <input v-model="newAdmin.phone" placeholder="请输入手机号" required />
          </div>
          <div class="form-group">
            <label>权限：</label>
            <select v-model="newAdmin.role">
              <option value="正常">正常</option>
              <option value="超级管理员">超级管理员</option>
              <option value="只读">只读</option>
            </select>
          </div>
          <div class="modal-footer">
            <button @click="showEditModal = false" class="btn btn-secondary">取消</button>
            <button @click="confirmEdit" class="btn btn-primary">确认</button>
          </div>
        </div>
      </div>

      <!-- 删除确认弹窗 -->
      <div v-if="showDeleteModal" class="modal-overlay">
        <div class="modal-content">
          <h3>删除确认</h3>
          <p>确定要删除管理员 "<strong>{{ itemToDelete?.username }}</strong>" 吗？此操作不可恢复！</p>
          <div class="modal-footer">
            <button @click="showDeleteModal = false" class="btn btn-secondary">取消</button>
            <button @click="confirmDelete" class="btn btn-danger">确定删除</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import api from '@/api'

const router = useRouter()
const admins = ref([])
const searchKeyword = ref('')
const selectedItem = ref(null)
const showAddModal = ref(false)
const showEditModal = ref(false)
const showDeleteModal = ref(false)
const itemToDelete = ref(null)

const newAdmin = ref({
  username: '',
  phone: '',
  role: '正常'
})

const expanded = reactive({ user: true, product: false })

// 获取管理员列表
const fetchAdmins = async () => {
  try {
    const res = await api.getAdminList({ keyword: searchKeyword.value })
    const rows = Array.isArray(res?.data) ? res.data : (Array.isArray(res) ? res : [])
    admins.value = rows.map(u => ({
      id: u.userId,
      username: u.userName,
      phone: u.phone,
      role: u.roles && u.roles.includes('ROLE_ADMIN') ? '超级管理员' : '正常' // 简化显示
    }))
  } catch (error) {
    console.error('获取管理员列表失败:', error)
  }
}

const filteredAdmins = computed(() => {
  const keyword = searchKeyword.value.trim().toLowerCase()
  if (!keyword) {
    return admins.value
  }
  return admins.value.filter(item =>
    item.username?.toLowerCase().includes(keyword) ||
    item.phone?.includes(keyword)
  )
})

// 计算是否表单有效
const isValid = computed(() => {
  return (
    newAdmin.value.username.trim() &&
    newAdmin.value.phone.trim()
  )
})

const selectItem = (item) => {
  selectedItem.value = item
}

const onFocus = (e) => {
  e.target.select()
}

const cancelAdd = () => {
  showAddModal.value = false
  resetNewAdmin()
}

const resetNewAdmin = () => {
  newAdmin.value = {
    username: '',
    phone: '',
    role: '正常'
  }
}

const confirmAdd = async () => {
  if (!isValid.value) {
    alert('请填写必填项（管理员名、手机号）')
    return
  }
  try {
    await api.createAdmin({
      userName: newAdmin.value.username,
      phone: newAdmin.value.phone,
      password: '123456@Password', // 默认初始密码
      role: newAdmin.value.role
    })
    showAddModal.value = false
    resetNewAdmin()
    fetchAdmins()
    alert('管理员创建成功，默认密码：123456@Password')
  } catch (error) {
    alert(error.message || '创建失败')
  }
}

const openEditModal = (item) => {
  newAdmin.value = { ...item }
  showEditModal.value = true
}

const confirmEdit = async () => {
  try {
    // 转换角色名为后端识别的字段，或者后端已经做了映射
    // 假如需要更新基本信息
    await api.updateUserInfo(newAdmin.value.id, {
      userName: newAdmin.value.username,
      phone: newAdmin.value.phone,
      role: newAdmin.value.role
    })
    showEditModal.value = false
    resetNewAdmin()
    fetchAdmins()
    alert('修改成功')
  } catch (error) {
    alert(error.message || '修改失败')
  }
}

const openDeleteModal = (item) => {
  itemToDelete.value = item
  showDeleteModal.value = true
}

const confirmDelete = async () => {
  if (itemToDelete.value) {
    try {
      await api.deleteUser(itemToDelete.value.id)
      showDeleteModal.value = false
      itemToDelete.value = null
      fetchAdmins()
      alert('删除成功')
    } catch (error) {
      alert(error.message || '删除失败')
    }
  }
}

const toggleMenu = (key) => {
  expanded[key] = !expanded[key]
}

const handleLogout = () => {
  api.logout().finally(() => {
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    router.push('/admin-login')
  })
}

onMounted(() => {
  fetchAdmins()
})

</script>

<style scoped>
/* ========== 布局基础 ========== */
@import '@/CSS/ManagerPublicCss.css';

/* ========== 右侧内容 ========== */
@import '@/CSS/ManagerPageAdminList.css';
</style>